// profile.js - 个人中心页面JavaScript代码（无Token版）

// API基础URL
const API_BASE_URL = 'http://localhost:8080';
let currentUser = null;


// 获取用户信息
async function fetchUserProfile(userId) {
    try {
        const response = await fetch(`${API_BASE_URL}/api/users/${userId}`);
        
        if (!response.ok) {
            if (response.status === 401) {
                Auth.isLoggedIn();
                window.location.href = 'login.html';
                return;
            }
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const responseData = await response.json();
        const userData = responseData.data;

        // 格式化日期
        if (userData.birthDate) {
            userData.formattedBirthDate = formatDate(userData.birthDate);
        }
        if (userData.registerTime) {
            userData.formattedRegisterTime = formatDateTime(userData.registerTime);
        }
        if (userData.lastLoginTime) {
            userData.formattedLastLoginTime = formatDateTime(userData.lastLoginTime);
        }

        return userData;
    } catch (error) {
        console.error('获取用户信息失败:', error);
        throw error;
    }
}

// 更新用户信息显示
function updateProfileDisplay(user) {
    if (!user) return;
    
    document.getElementById('profileTitle').textContent = user.real_name || '未设置';
    document.getElementById('profileSubtitle').textContent = `用户ID: ${user.id}`;
    
    const avatarElement = document.getElementById('profileAvatar');
    if (user.avatarPath) {
        avatarElement.src = user.avatarPath;
        avatarElement.onerror = () => {
            avatarElement.src = './static/imgs/user.png';
        };
    }
    
    const fields = {
        'infoUsername': user.username,
        'infoRealName': user.real_name || '未设置',
        'infoGender': user.gender === 'male' ? '男' : '女',
        'infoBirthDate': user.formattedBirthDate || '未设置',
        'infoPhone': formatPhoneNumber(user.phone),
        'infoLoginTime': user.formattedLastLoginTime || '未设置',
        'infoIdCard': formatIdCard(user.id_card),
        'infoRegisterTime': user.formattedRegisterTime || '未设置'
    };
    
    Object.entries(fields).forEach(([id, value]) => {
        const element = document.getElementById(id);
        if (element) element.textContent = value;
    });
}

// 初始化编辑表单
function initEditForm(user) {
    const fields = {
        'editUsername': user.username,
        'editRealName': user.real_name || '',
        'editGender': user.gender,
        'editBirthDate': user.birthDate ? user.birthDate.split('T')[0] : '',
        'editPhone': user.phone || '',
        'editIdCard': user.id_card || ''
    };
    
    Object.entries(fields).forEach(([id, value]) => {
        const element = document.getElementById(id);
        if (element) element.value = value;
    });
}

// ==================== API操作 ====================

async function updateUserProfile(userId, profileData) {
    try {
        const response = await fetch(`${API_BASE_URL}/api/users/${userId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                real_name: profileData.realName,
                gender: profileData.gender,
                birth_date: profileData.birthDate,
                phone: profileData.phone
            })
        });

        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.message || '更新失败');
        }

        return await response.json();
    } catch (error) {
        console.error('更新用户信息失败:', error);
        throw error;
    }
}

async function changePassword(userId, passwordData) {
    try {
        const response = await fetch(`${API_BASE_URL}/api/users/${userId}/password`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                current_password: passwordData.currentPassword,
                new_password: passwordData.newPassword
            })
        });

        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.message || '密码修改失败');
        }

        return await response.json();
    } catch (error) {
        console.error('修改密码失败:', error);
        throw error;
    }
}

// ==================== 辅助函数 ====================

function formatPhoneNumber(phone) {
    if (!phone) return '未设置';
    return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1*​**​*$2');
}

function formatIdCard(idCard) {
    if (!idCard) return '未设置';
    return idCard.replace(/(\d{6})\d{8}(\w{4})/, '$1*​**​*​**​**$2');
}

function formatDate(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN');
}

function formatDateTime(dateTimeString) {
    if (!dateTimeString) return '';
    const date = new Date(dateTimeString);
    return date.toLocaleString('zh-CN');
}

// ==================== 模态框控制 ====================

function openEditModal() {
    document.getElementById('editModal').style.display = 'block';
}

function openPasswordModal() {
    document.getElementById('passwordModal').style.display = 'block';
    document.getElementById('currentPassword').focus();
}

function closeModal(modalId) {
    document.getElementById(modalId).style.display = 'none';
}

function showLogoutConfirmation() {
    document.getElementById('logoutModal').style.display = 'block';
}

// 简化版退出登录（无API调用）
function confirmLogout() {
    const confirmBtn = document.querySelector('#logoutModal .btn-confirm');
    confirmBtn.disabled = true;
    confirmBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 退出中...';

    // 直接清除本地状态
    Auth.clearAuth();
    
    // 跳转到登录页
    window.location.href = 'login.html';
}

// ==================== 事件监听 ====================

window.onclick = function(event) {
    if (event.target.className === 'modal') {
        event.target.style.display = 'none';
    }
}

document.getElementById('editForm')?.addEventListener('submit', async (e) => {
    e.preventDefault();

    const submitBtn = e.target.querySelector('button[type="submit"]');
    submitBtn.disabled = true;
    submitBtn.textContent = '保存中...';

    try {
        const formData = {
            realName: document.getElementById('editRealName').value,
            gender: document.getElementById('editGender').value,
            birthDate: document.getElementById('editBirthDate').value,
            phone: document.getElementById('editPhone').value
        };

        const response = await updateUserProfile(currentUser.id, formData);

        currentUser = {
            ...currentUser,
            ...response.data
        };
        updateProfileDisplay(currentUser);

        alert('资料修改成功！');
        closeModal('editModal');
    } catch (error) {
        alert(`资料修改失败: ${error.message}`);
    } finally {
        submitBtn.disabled = false;
        submitBtn.textContent = '保存更改';
    }
});

document.getElementById('passwordForm')?.addEventListener('submit', async (e) => {
    e.preventDefault();

    const submitBtn = e.target.querySelector('button[type="submit"]');
    submitBtn.disabled = true;
    submitBtn.textContent = '修改中...';

    const currentPassword = document.getElementById('currentPassword').value;
    const newPassword = document.getElementById('newPassword').value;
    const confirmPassword = document.getElementById('confirmPassword').value;

    if (newPassword !== confirmPassword) {
        alert('两次输入的新密码不一致！');
        submitBtn.disabled = false;
        submitBtn.textContent = '确认修改';
        return;
    }

    try {
        await changePassword(currentUser.id, {
            currentPassword: currentPassword,
            newPassword: newPassword
        });

        alert('密码修改成功，请重新登录');
        Auth.clearAuth();
        window.location.href = 'login.html';
    } catch (error) {
        alert(`密码修改失败: ${error.message}`);
    } finally {
        submitBtn.disabled = false;
        submitBtn.textContent = '确认修改';
    }
});

// ==================== 初始化 ====================

document.addEventListener('DOMContentLoaded', async () => {
    try {
        if (!Auth.isLoggedIn()) {
            alert('请先登录');
            window.location.href = 'login.html';
            return;
        }

        const userId = Auth.getCurrentUserId();
        currentUser = await fetchUserProfile(userId);
        
        if (!currentUser) {
            throw new Error('无法获取用户信息');
        }
        
        updateProfileDisplay(currentUser);
        initEditForm(currentUser);
        
        const logoutButton = document.getElementById('logoutButton');
        if (logoutButton) {
            logoutButton.style.display = 'block';
            logoutButton.addEventListener('click', (e) => {
                e.preventDefault();
                showLogoutConfirmation();
            });
        }

    } catch (error) {
        console.error('初始化失败:', error);
        Auth.clearAuth();
        alert('会话已过期，请重新登录');
        window.location.href = 'login.html';
    }
});